package com.ims.core.erp;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ims.common.core.domain.entity.SysDictData;
import com.ims.common.core.redis.RedisCache;
import com.ims.common.enums.BusinessStatus;
import com.ims.common.exception.base.BaseException;
import com.ims.common.utils.DateUtils;
import com.ims.common.utils.DictUtils;
import com.ims.common.utils.StringUtils;
import com.ims.common.utils.http.ErpHttpUtils;
import com.ims.common.utils.spring.SpringUtils;
import com.ims.common.utils.uuid.IdUtils;
import com.ims.core.doc.domain.TSalOrder;
import com.ims.core.doc.domain.TSalOrderEntry;
import com.ims.core.doc.domain.TScSettlebill;
import com.ims.core.doc.domain.TScSettlebillEntry;
import com.ims.core.enums.IsTax;
import com.ims.core.enums.SalInvoiceType;
import com.ims.core.enums.SettlebillStatus;
import com.ims.core.inconfig.domain.TSrmSupplier;
import com.ims.core.saleconfig.domain.TSalBuyer;
import com.ims.core.saleconfig.domain.TSalMaterial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.ws.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ErpApiUtil {
    private static final Logger log = LoggerFactory.getLogger(ErpApiUtil.class);

    private static final String ERP_API_DOMAIN = "http://192.168.1.5/IDORequestService/MGRestService.svc/json/";

    private static final String environment = "TEST_ALL";
    //  private static final String environment = "SBN";

    private static final String ERP_TOKEN_CACHE_KEY = "rs_erp_token";

    // 24小时，单位分
    private static final Integer ERP_TOKEN_CAPTCHA_EXPIRATION = 1440;


    /**
     * 获取token
     * @return
     */
    public static String getToken(){
        // 缓存获取token
//        String token = SpringUtils.getBean(RedisCache.class).getCacheObject(ERP_TOKEN_CACHE_KEY);
//        if(!StringUtils.isEmpty(token)){
//            return token;
//        }

        String UserId = "SL_Internal";
        String Password = "sbnit001,.";
        Map headerMap = new HashMap<>();
        headerMap.put("UserId", UserId);
        headerMap.put("Password", Password);
        headerMap.put("Password", Password);

        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "token/" + environment, headerMap);
        String token = "";
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            token = resJson.getString("Token");
            // 缓存24小时
            // SpringUtils.getBean(RedisCache.class).setCacheObject(ERP_TOKEN_CACHE_KEY, token, ERP_TOKEN_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("ERP获取Token接口失败");
            e.getMessage();
        }
        if(StringUtils.isEmpty(token)){
            throw new BaseException("ERP获取Token接口失败");
        }
        return token;
    }


    /**
     * 1.计量单位码
     * 存字典表，只需存 UM 及 Description 字段内容，其它都为固定或顺序排序号，1天调用一次
     * insert into sys_dict_data(dict_sort,dict_label,dict_value,dict_type,remark)values(顺序号,Description,UM,'unit','物料单位')
     * 存储时  调用函数   select [dbo].[getSysdictdataName]('unit','A')   ，A处理传UM值 存在时不做插入，不更新
     * @return
     */
    public static List<SysDictData> getSLUM(){

        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLUMs/UM,Description/adv/", headerMap);
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            System.out.println("计量单位返回：");
            System.out.println(resStr);
            return convertToDict(resJson.getJSONArray("Items"), "UM", "Description", "unit");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取计量单位码接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 2.物料
     * @return
     */
    public static List<TSalMaterial> getErpItems(){
        List<TSalMaterial> materialList = new ArrayList<>();
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLItems/CommCode,Description,Item,MatlType,Stat,UM,itmUf_comm_code,Charfld1/adv/?rowcap=0&filter=ProductCode%20Like%20'V6%'", headerMap);
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            materialList.addAll(convertToMaterial(resJson.getJSONArray("Items")));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取物料接口失败");
            e.getMessage();
        }
        return materialList;
    }

    /**
     * 3.货币代码
     * 存字典表，只需存CurrCode及 Description 字段内容，其它都为固定或顺序排序号，1天调用一次
     * @return
     */
    public static List<SysDictData> getCurrencyCodes(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLCurrencyCodes/CurrCode,Description/adv/", headerMap);
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            System.out.println("货币代码返回：");
            System.out.println(resStr);
            return convertToDict(resJson.getJSONArray("Items"), "CurrCode", "Description", "currency_code");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取货币代码接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 4.供应商状态代码
     * 存字典表，只需存 Stat 及 Description 字段内容，其它都为固定或顺序排序号，1天调用一次
     * @return
     */
    public static List<SysDictData> getVendorStatuses(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLVendorStatuses/Stat,Description/adv/", headerMap);
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            System.out.println("供应商状态代码返回：");
            System.out.println(resStr);
            return convertToDict(resJson.getJSONArray("Items"),"Stat","Description", "supplier_status");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取供应商状态代码接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 5.账单条款
     * 存字典表，只需存 TermsCode 及 Description 字段内容，其它都为固定或顺序排序号，1天调用一次
     * @return
     */
    public static List<SysDictData> getTerms(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLTerms/TermsCode,Description/adv/", headerMap);
        // 解析
        try {
            System.out.println("账单条款返回：");
            System.out.println(resStr);
            JSONObject resJson = JSONObject.parseObject(resStr);
            return convertToDict(resJson.getJSONArray("Items"), "TermsCode", "Description", "terms_code");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取账单条款接口失败");
            e.getMessage();
        }
        return null;
    }



    /**
     * 6.税码
     * 存字典表，只需存 taxCode 及 TaxRate 字段内容，其它都为固定或顺序排序号，1天调用一次
     * @return
     */
    public static List<SysDictData> getTaxCode(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        // http://60.169.71.191:10112/IDORequestService/MGRestService.svc/json/SLTaxcodes/TaxSystem,TaxCode,TaxRate/adv/
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLTaxcodes/TaxSystem,TaxCode,TaxRate,Description/adv/", headerMap);
        // 解析
        try {
            System.out.println("税码：");
            System.out.println(resStr);
            JSONObject resJson = JSONObject.parseObject(resStr);
            return convertToTaxDict(resJson.getJSONArray("Items"), "TaxRate", "Description", "TaxCode", "tax_rate");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取账单条款接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 6.供应商
     * 存表  t_srm_supplier 标颜色行的字段存储对应的 电票字段
     * CustNum 供应商编码存在时更新，不存在时插入，1小时调用1次
     * @return
     */
    public static List<TSrmSupplier> getVendors(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLVendors/Contact,CurrCode,Phone,Stat,TermsCode,VadRAddr_1,VadRAddr_3,VadRAddr_4,VadRCity,VadRCounty,VendNum,Name/adv/?rowcap=0", headerMap);
        // 解析
        try {
            System.out.println("供应商返回：");
            System.out.println(resStr);
            JSONObject resJson = JSONObject.parseObject(resStr);
            return  convertToSupplier(resJson.getJSONArray("Items"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取供应商接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 7.客户
     * 存表  t_sal_buyer 标颜色行的字段存储对应的 电票字段，没标颜色的ERP字段不用管
     * CustNum 客户编码存在时更新，不存在时插入，1小时调用1次
     * @return
     */
    public static List<TSalBuyer> getCustomers(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLCustomers/Addr_1,Addr_2,Addr_3,Addr_4,City,CustNum,Name,Phone_1/adv/?rowcap=0", headerMap);
        // 解析
        try {
            System.out.println("客户返回：");
            System.out.println(resStr);
            JSONObject resJson = JSONObject.parseObject(resStr);

            return  convertToBuyer(resJson.getJSONArray("Items"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取Token接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 8.销售单
     * 存表  t_sal_order
     * ordereNo 订单号存在时更新，不存在时插入，1小时调用1次
     * @return
     */
    public static List<TSalOrder> getOrders(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String orderResStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLCos/CoNum,CustNum,CustSeq,BillToName,TermsCode,Stat,OrderDate,CustPo,Type,Slsman,IncludeTaxInPrice,EndUserType,Contact,CurrCode,TaxCode1,Price/adv/?rowcap=0&filter=Stat='O'", headerMap);
        // 解析
        try {
            JSONObject orderResJson = JSONObject.parseObject(orderResStr);
            return  convertToOrder(orderResJson.getJSONArray("Items"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取Token接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 9.结算单
     * 存表  t_sal_order
     * InvNum 发票号存在时更新，不存在时插入，1小时调用1次
     * @return
     */
    public static List<TScSettlebill> getSettlebill(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String settlebillResStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "RSSLArinvs/CustNum,Type,InvNum,ApplyToInvNum,InvDate,DueDate,TermsCode,Amount,Freight,MiscCharges,SalesTax,DerAmtTotInv,IncludeTaxInPrice,CadbtCurrCode,ExchRate,TaxDate,PostFromCo,memo/adv/?rowcap=0", headerMap);
        String settlebillEntryResStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "RSSLInvItemAlls/InvNum,DerCustPo,InvhdrSlsman,InvhdrExchRate,DerCoNum,CoLine,Item,DerDescription,QtyInvoiced,CustaddrCurrCode,Price,DerExtendedPrice,UM,ItmTaxCode1,CommCode,CommCodeDescription,UMDesc,Spec/adv/?rowcap=0", headerMap);
        // 解析
        try {
            JSONObject settlebillResJson = JSONObject.parseObject(settlebillResStr);
            JSONObject settlebillEntryResJson = JSONObject.parseObject(settlebillEntryResStr);
            return  convertToSettlebill(settlebillResJson.getJSONArray("Items"), settlebillEntryResJson.getJSONArray("Items"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取Token接口失败");
            e.getMessage();
        }
        return null;
    }

    /**
     * 税码
     * @return
     */
    public static JSONArray getTaxcodes(){
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        String resStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLTaxcodes/TaxSystem,TaxCode,TaxRate/adv/", headerMap);
        // 解析
        try {
            JSONObject resJson = JSONObject.parseObject(resStr);
            return  resJson.getJSONArray("Items");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERP获取Token接口失败");
            e.getMessage();
        }
        return null;
    }


    /**
     * 发票状态回写
     * @return
     */
    public static String updateSettle(String invNum, String comment){
        // 解析
        Map headerMap = new HashMap<>();
        headerMap.put("Authorization", getToken());
        // step 1 GET 从发票借项贷项接口获取ItemId
        invNum = invNum.replaceAll(" ", "%20");
        String settlebillResStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "RSSLArinvs/InvNum/adv/?rowcap=0&filter=InvNum=" + invNum, headerMap);
        JSONObject settlebillResJson = JSONObject.parseObject(settlebillResStr);
        JSONArray items = settlebillResJson.getJSONArray("Items");
        String itemId = "";
        if(items.size() == 0){
            log.error("无法根据{}找到ERP发票", invNum);
        } else {
            for(Object itemObj : items){
                JSONArray itemArry = (JSONArray) itemObj;
                for(Object item : itemArry){
                    JSONObject itemJo = (JSONObject) item;
                    // 客户编码
                    if(itemJo.getString("Name").equals("_ItemId")){
                        itemId = (itemJo.getString("Value"));
                    }
                }
            }
        }
        if(StringUtils.isEmpty(itemId)){
            log.error("无法根据{}找到ERP发票itemId", invNum);
        } else {
            // step 2 PUT 根据ItemId修改结算单的状态
            JSONObject params = new JSONObject();
            params.put("Action", 2);
            params.put("ItemId", itemId);
            JSONArray properties = new JSONArray();
            JSONObject statuParam = new JSONObject();
            statuParam.put("IsNull", false);
            statuParam.put("Modified", true);
            statuParam.put("Name", "CNVATStatus");
            statuParam.put("Value", "C");
            properties.add(statuParam);
            JSONObject commentParam = new JSONObject();
            commentParam.put("IsNull", false);
            commentParam.put("Modified", true);
            commentParam.put("Name", "CNComment");
            commentParam.put("Value", comment);
            properties.add(commentParam);
            params.put("Properties", properties);
            return ErpHttpUtils.sendPutWithHeadParams(ERP_API_DOMAIN + "SLArinvs/updateitem", params.toJSONString(), headerMap);
        }
        return null;
    }

    /**
     *  ======================================================== 私有方法 =============================================
     */

    /**
     * erp返回的基础数据转为系统内DICT类型
     * @param jsonArray
     * @return
     */
    private static List<SysDictData> convertToDict(JSONArray jsonArray, String dictValueName, String dictLabelName, String dictType){
        List<SysDictData> sysDictDataList = new ArrayList<>();
        Long sort = 0L;
        for(Object itemO : jsonArray){
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictSort(sort++);
            sysDictData.setDictType(dictType);
            sysDictData.setStatus("0");
            sysDictData.setCreateBy("erp");
            sysDictData.setCreateTime(DateUtils.getNowDate());
            JSONArray itemJa = (JSONArray) itemO;
            for(Object co : itemJa){
                JSONObject cjo = (JSONObject) co;
                if(cjo.getString("Name").equals(dictValueName)){
                    sysDictData.setDictValue(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals(dictLabelName)){
                    sysDictData.setDictLabel(cjo.getString("Value"));
                }
            }
            sysDictDataList.add(sysDictData);
        }
        return sysDictDataList;
    }


    /**
     * erp返回的基础数据转为系统内DICT类型(税率)
     * @param jsonArray
     * @return
     */
    private static List<SysDictData> convertToTaxDict(JSONArray jsonArray, String dictValueName, String dictLabelName, String dictOrgValue, String dictType){
        List<SysDictData> sysDictDataList = new ArrayList<>();
        Long sort = 0L;
        for(Object itemO : jsonArray){
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictSort(sort++);
            sysDictData.setDictType(dictType);
            sysDictData.setStatus("0");
            sysDictData.setCreateBy("erp");
            sysDictData.setCreateTime(DateUtils.getNowDate());
            JSONArray itemJa = (JSONArray) itemO;
            for(Object co : itemJa){
                JSONObject cjo = (JSONObject) co;
                if(cjo.getString("Name").equals(dictValueName)){
                    sysDictData.setDictValue(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals(dictLabelName)){
                    sysDictData.setDictLabel(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals(dictOrgValue)){
                    sysDictData.setListClass(cjo.getString("Value"));
                }
            }
            sysDictDataList.add(sysDictData);
        }
        return sysDictDataList;
    }


    /**
     * erp返回的基础数据转为系统内购方
     * @param jsonArray
     * @return
     */
    private static List<TSalBuyer> convertToBuyer(JSONArray jsonArray){
        List<TSalBuyer> tSalBuyerList = new ArrayList<>();
        for(Object itemO : jsonArray){
            TSalBuyer salBuyer = new TSalBuyer();
            salBuyer.setIsEnabled(1L);
            salBuyer.setIsEnabledName("有效");
            salBuyer.setCreateBy("erp");
            salBuyer.setCreateTime(DateUtils.getNowDate());

            JSONArray itemJa = (JSONArray) itemO;
            for(Object co : itemJa){
                JSONObject cjo = (JSONObject) co;
                if(cjo.getString("Name").equals("Addr_1")){ // buyer_address
                    salBuyer.setBuyerAddress(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Addr_2")){ //buyer_bank_address
                    salBuyer.setBuyerBankAddress(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Addr_3")){ //buyer_bank
                    salBuyer.setBuyerBank(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Addr_4")){ //buyer_account
                    salBuyer.setBuyerAccount(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("City")){ //buyer_number
                    salBuyer.setBuyerNumber(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("CustNum")){ // buyer_code
                    salBuyer.setBuyerId(cjo.getString("Value"));
                    salBuyer.setBuyerCode(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Name")){ //buyer_name
                    salBuyer.setBuyerName(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Phone_1")){ //buyer_tel
                    salBuyer.setBuyerTel(cjo.getString("Value"));
                }
            }
            tSalBuyerList.add(salBuyer);
        }
        return tSalBuyerList;
    }

    /**
     * erp返回的基础数据转为系统内物料
     * @param jsonArray
     * @return
     */
    private static List<TSalMaterial> convertToMaterial(JSONArray jsonArray){
        List<TSalMaterial> tSalMaterialList = new ArrayList<>();
        for(Object itemO : jsonArray){
            TSalMaterial salMaterial = new TSalMaterial();
            salMaterial.setMaterialId(IdUtils.simpleUUID());
            salMaterial.setCreateBy("erp");
            salMaterial.setCreateTime(DateUtils.getNowDate());
            JSONArray itemJa = (JSONArray) itemO;
            for(Object co : itemJa){
                JSONObject cjo = (JSONObject) co;
                if(cjo.getString("Name").equals("CommCode")){

                }
                if(cjo.getString("Name").equals("Description")){
                    salMaterial.setMaterialName(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Item")){

                    salMaterial.setMaterialCode(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("MatlType")){
                    salMaterial.setMaterialType(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        salMaterial.setMaterialTypeName(DictUtils.getDictLabel("material_type", cjo.getString("Value")));
                    }
                }
                if(cjo.getString("Name").equals("Stat")){
                    salMaterial.setStatus(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        salMaterial.setStatusName(DictUtils.getDictLabel("material_status", cjo.getString("Value")));
                    }
                }
                if(cjo.getString("Name").equals("UM")){
                    salMaterial.setUnit(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        salMaterial.setUnitName(DictUtils.getDictLabel("unit", cjo.getString("Value")));
                    }
                }
                if(cjo.getString("Name").equals("itmUf_comm_code")){
                    salMaterial.setTaxCode(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Charfld1")){
                    salMaterial.setSpecificatCode(cjo.getString("Value"));
                }
            }
            tSalMaterialList.add(salMaterial);
        }
        return tSalMaterialList;
    }


    /**
     * erp返回的基础数据转为系统内供应商
     * @param jsonArray
     * @return
     */
    private static List<TSrmSupplier> convertToSupplier(JSONArray jsonArray){
        List<TSrmSupplier> srmSupplierArrayList = new ArrayList<>();
        for(Object itemO : jsonArray){
            TSrmSupplier srmSupplier = new TSrmSupplier();
            srmSupplier.setCreateBy("erp");
            srmSupplier.setCreateTime(DateUtils.getNowDate());

            JSONArray itemJa = (JSONArray) itemO;
            for(Object co : itemJa){
                JSONObject cjo = (JSONObject) co;
                if(cjo.getString("Name").equals("Contact")){
                    srmSupplier.setContactBy(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("CurrCode")){
                    srmSupplier.setCurrencyCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        srmSupplier.setCurrencyName(DictUtils.getDictLabel("currency_code", cjo.getString("Value")));
                    }
                }
                if(cjo.getString("Name").equals("Phone")){
                    srmSupplier.setTel(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Stat")){
                    srmSupplier.setSupplierStatus(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        srmSupplier.setSupplierStatusName(DictUtils.getDictLabel("supplier_status", cjo.getString("Value")));
                    }
                    // srmSupplier.setSupplierStatusName(DictUtils.getDictLabel("supplier_status", cjo.getString("Value")));
                }
                if(cjo.getString("Name").equals("TermsCode")){
                    srmSupplier.setTermCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        srmSupplier.setTermName(DictUtils.getDictLabel("terms_code", cjo.getString("Value")));
                    }
                }
                if(cjo.getString("Name").equals("VadRAddr_1")){
                    srmSupplier.setAddress(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("VadRAddr_3")){
                    srmSupplier.setBankName(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("VadRAddr_4")){
                    srmSupplier.setAccountNo(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("VadRCity")){
                    srmSupplier.setProvinceName(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("VadRCounty")){
                    srmSupplier.setCityName(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("VendNum")){
                    srmSupplier.setSupplierCode(cjo.getString("Value"));
                }
                if(cjo.getString("Name").equals("Name")){
                    srmSupplier.setSupplierName(cjo.getString("Value"));
                }
            }
            srmSupplierArrayList.add(srmSupplier);
        }
        return srmSupplierArrayList;
    }

    /**
     * 转换为销售订单
     * @param orderJsonArray 订单头
     * @return
     */
    private static List<TSalOrder> convertToOrder(JSONArray orderJsonArray){
        List<TSalOrder> orderList = new ArrayList<>();
        for(Object orderJo : orderJsonArray){
            TSalOrder tSalOrder = new TSalOrder();
            tSalOrder.setCreateBy("erp");
            tSalOrder.setCreateTime(DateUtils.getNowDate());
            JSONArray orderItemJa = (JSONArray) orderJo;
            for(Object oij : orderItemJa){
                JSONObject cjo = (JSONObject) oij;
                // 客户订单号
                if(cjo.getString("Name").equals("CoNum")){
                    tSalOrder.setOrderNo(cjo.getString("Value"));
                }
                // 客户编码
                if(cjo.getString("Name").equals("CustNum")){
                    tSalOrder.setBuyerCode(cjo.getString("Value"));
                }
                // 客户名称
                if(cjo.getString("Name").equals("BillToName")){
                    tSalOrder.setBuyerName(cjo.getString("Value"));
                }
                // 账单条款
                if(cjo.getString("Name").equals("TermsCode")){
                    tSalOrder.setTermsCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))){
                        tSalOrder.setTermsName(DictUtils.getDictLabel("terms_code", cjo.getString("Value")));
                    }
                }
                // 订购状态
                if(cjo.getString("Name").equals("Stat")){
                    tSalOrder.setOrderStatus(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))){
                        tSalOrder.setOrderStatusName(DictUtils.getDictLabel("order_status", cjo.getString("Value")));
                    }
                }

                // 订单日期
                if(cjo.getString("Name").equals("OrderDate")){
                    tSalOrder.setOrderDate(DateUtils.dateTime("yyyyMMdd HH:mm:ss.SSS", cjo.getString("Value")));
                }
                // 客户采购单号
                if(cjo.getString("Name").equals("CustPo")){
                    tSalOrder.setPoNo(cjo.getString("Value"));
                }
                // 订单类型
                if(cjo.getString("Name").equals("Type")){
                    tSalOrder.setOrderType(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))){
                        tSalOrder.setOrderTypeName(DictUtils.getDictLabel("order_type", cjo.getString("Value")));
                    }
                }
                // 销售员
                if(cjo.getString("Name").equals("Slsman")){
                    tSalOrder.setSaleName(cjo.getString("Value"));
                }
                // 含税标识
                if(cjo.getString("Name").equals("IncludeTaxInPrice")){
                    tSalOrder.setIsTax(Integer.parseInt(cjo.getString("Value")));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))){
                        tSalOrder.setIsTaxName(DictUtils.getDictLabel("is_tax", cjo.getString("Value")));
                    }
                }
                // 联系人
                if(cjo.getString("Name").equals("Contact")){
                    tSalOrder.setContractName(cjo.getString("Value"));
                }
                // 币别
                if(cjo.getString("Name").equals("CurrCode")){
                    tSalOrder.setCurrencyCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tSalOrder.setCurrencyName(DictUtils.getDictLabel("currency_code", cjo.getString("Value")));
                    }
                }
                // 税码
                if(cjo.getString("Name").equals("TaxCode1")){
                    tSalOrder.setTaxCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))){
                        tSalOrder.setTaxRate(DictUtils.getDictLabel("tax_code", cjo.getString("Value")));
                    }
                }
                // 预估总价
                if(cjo.getString("Name").equals("Price")){
                    tSalOrder.setTotalAmount(cjo.getBigDecimal("Value"));
                }
            }
            // 明细
            List<TSalOrderEntry> orderEntryList = new ArrayList<>();

            Map headerMap = new HashMap<>();
            headerMap.put("Authorization", getToken());
            String coNum = tSalOrder.getOrderNo().replaceAll(" ", "%20");
            String orderEntryResStr = ErpHttpUtils.sendGetWithHeadParams(ERP_API_DOMAIN + "SLCoitems/CoNum,CoLine,Item,Description,QtyOrderedConv,UM,PriceConv,DueDate,Stat,DerQtyShippedConv,DerQtyInvoicedConv/adv/?rowcap=0&filter=CoNum='" + coNum + "'", headerMap);
            JSONObject orderEntryResJson = JSONObject.parseObject(orderEntryResStr);
            JSONArray orderEntryJsonArray = orderEntryResJson.getJSONArray("Items");

            for(Object orderEntryJo : orderEntryJsonArray){
                JSONArray orderEntryItemJa = (JSONArray) orderEntryJo;
                boolean isSameOrder = false;
                // 循环字段
                for(Object oeij : orderEntryItemJa){
                    JSONObject cejo = (JSONObject) oeij;
                    // 客户订单号
                    if(cejo.getString("Name").equals("CoNum")){
                        // 订单号一致的明细
                        if(cejo.getString("Value").equals(tSalOrder.getOrderNo())){
                            isSameOrder = true;
                        }
                    }
                }
                if(isSameOrder){
                    TSalOrderEntry tSalOrderEntry = new TSalOrderEntry();
                    // 循环字段
                    for(Object oeij : orderEntryItemJa){
                        JSONObject cejo = (JSONObject) oeij;
                        // 客户订单号
                        if(cejo.getString("Name").equals("CoNum")){
                            tSalOrderEntry.setOrderNo(cejo.getString("Value"));
                        }
                        // 客户订单行
                        if(cejo.getString("Name").equals("CoLine")){
                            tSalOrderEntry.setLineNo(Long.parseLong(cejo.getString("Value")));
                        }
                        // 物料
                        if(cejo.getString("Name").equals("Item")){
                            tSalOrderEntry.setProductCode(cejo.getString("Value"));
                        }
                        // 物料描述
                        if(cejo.getString("Name").equals("Description")){
                            tSalOrderEntry.setProductName(cejo.getString("Value"));
                            if(StringUtils.isEmpty(cejo.getString("Value"))){
                                tSalOrderEntry.setProductName(tSalOrderEntry.getProductCode());
                            }
                        }
                        // 订购数量
                        if(cejo.getString("Name").equals("QtyOrderedConv")){
                            tSalOrderEntry.setOrderQty(new BigDecimal(cejo.getString("Value")));
                        }
                        // 订购单位
                        if(cejo.getString("Name").equals("UM")){
                            tSalOrderEntry.setUnitCode(cejo.getString("Value"));
                            if(StringUtils.isNotEmpty(cejo.getString("Value"))){
                                tSalOrderEntry.setUnit(DictUtils.getDictLabel("unit", cejo.getString("Value")));
                            }
                        }
                        // 价格
                        if(cejo.getString("Name").equals("PriceConv")){
                            tSalOrderEntry.setPrice(new BigDecimal(cejo.getString("Value")));
                        }
                        // 到期日期
                        if(cejo.getString("Name").equals("DueDate")){
                            if(StringUtils.isNotEmpty(cejo.getString("Value"))){
                                tSalOrderEntry.setDueDate(DateUtils.dateTime("yyyyMMdd HH:mm:ss.SSS", cejo.getString("Value")));
                            }
                        }
                        // 行状态
                        if(cejo.getString("Name").equals("Stat")){
                            tSalOrderEntry.setOrderStatus(cejo.getString("Value"));
                            if(StringUtils.isNotEmpty(cejo.getString("Value"))){
                                tSalOrderEntry.setOrderStatusName(DictUtils.getDictLabel("order_status", cejo.getString("Value")));
                            }
                        }
                        // 已发货数量
                        if(cejo.getString("Name").equals("DerQtyShippedConv")){
                            tSalOrderEntry.setQtyShipped(new BigDecimal(cejo.getString("Value")));
                        }
                        // 已开票数量
                        if(cejo.getString("Name").equals("DerQtyInvoicedConv")){
                            tSalOrderEntry.setQtyInvoiced(new BigDecimal(cejo.getString("Value")));
                        }
                    }
                    orderEntryList.add(tSalOrderEntry);
                } else {
                    continue;
                }
            }
            tSalOrder.setTSalOrderEntryList(orderEntryList);
            orderList.add(tSalOrder);
        }
        return orderList;
    }

    /**
     * 转换为结算单
     * @param settlebillJsonArray 结算单头
     * @param settlebillEntryJsonArray 结算单明细行
     * @return
     */
    private static List<TScSettlebill> convertToSettlebill(JSONArray settlebillJsonArray, JSONArray settlebillEntryJsonArray){
        // 查询默认销售方

        List<TScSettlebill> settlebillList = new ArrayList<>();
        for(Object settlebillJo : settlebillJsonArray){
            TScSettlebill tScSettlebill = new TScSettlebill();
            tScSettlebill.setSettlebillStatus(SettlebillStatus.UNCOMPLETED.getCode());
            tScSettlebill.setSettlebillStatusName(SettlebillStatus.UNCOMPLETED.getName());
            tScSettlebill.setCreateBy("erp");
            tScSettlebill.setCreateTime(DateUtils.getNowDate());
            // 默认增值税发票
            tScSettlebill.setInvoiceType(SalInvoiceType.ELECTRIC_SPECIAL.getCode());
            tScSettlebill.setInvoiceTypeName(SalInvoiceType.ELECTRIC_SPECIAL.getName());

            JSONArray settlebillItemJa = (JSONArray) settlebillJo;
            for(Object sij : settlebillItemJa){
                JSONObject cjo = (JSONObject) sij;
                // 客户编码
                if(cjo.getString("Name").equals("CustNum")){
                    tScSettlebill.setBuyerCode(cjo.getString("Value"));
                }
                // 形式发票类型
                if(cjo.getString("Name").equals("Type")){
                    tScSettlebill.setNatureType(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tScSettlebill.setNatureTypeName(DictUtils.getDictLabel("nature_type", cjo.getString("Value")));
                    }
                }
                // 发票号
                if(cjo.getString("Name").equals("InvNum")){
                    tScSettlebill.setOrderNo(cjo.getString("Value"));
                }
                // 应用于发票号
                if(cjo.getString("Name").equals("ApplyToInvNum")){
                    tScSettlebill.setSourceOrderNo(cjo.getString("Value"));
                }
                // 发票日期
                if(cjo.getString("Name").equals("InvDate")){
                    tScSettlebill.setSettleTime(DateUtils.dateTime("yyyyMMdd HH:mm:ss.SSS", cjo.getString("Value")));
                }
                // 到期日期
                if(cjo.getString("Name").equals("DueDate")){
                    tScSettlebill.setDueDate(DateUtils.dateTime("yyyyMMdd HH:mm:ss.SSS", cjo.getString("Value")));
                }
                // 账单条款
                if(cjo.getString("Name").equals("TermsCode")){
                    tScSettlebill.setTermsCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tScSettlebill.setTermsCodeName(DictUtils.getDictLabel("terms_code", cjo.getString("Value")));
                    }
                }
                // 金额
                if(cjo.getString("Name").equals("Amount")){
                    tScSettlebill.setAmount(new BigDecimal(cjo.getString("Value")));
                }
                // 运费
                if(cjo.getString("Name").equals("Freight")){
                    tScSettlebill.setFreightFee(new BigDecimal(cjo.getString("Value")));
                }
                // 杂费
                if(cjo.getString("Name").equals("MiscCharges")){
                    tScSettlebill.setMiscChargesFee(new BigDecimal(cjo.getString("Value")));
                }
                // 税
                if(cjo.getString("Name").equals("SalesTax")){
                    tScSettlebill.setTax(new BigDecimal(cjo.getString("Value")));
                }
                // 含税标识
                int isTax = 0;
                if(cjo.getString("Name").equals("IncludeTaxInPrice")){
                    isTax = Integer.parseInt(cjo.getString("Value"));
                    tScSettlebill.setIsTax(isTax);
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tScSettlebill.setIsTaxName(DictUtils.getDictLabel("is_tax", cjo.getString("Value")));
                    }
                }
                // 总金额
                if(cjo.getString("Name").equals("DerAmtTotInv")){
                    if(!StringUtils.isEmpty(cjo.getString("Value"))){
                        BigDecimal derAmtTotInv = new BigDecimal(cjo.getString("Value"));
                        tScSettlebill.setFee(derAmtTotInv);
                    }
                }

                // 币别
                if(cjo.getString("Name").equals("CadbtCurrCode")){
                    tScSettlebill.setCurrencyCode(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tScSettlebill.setCurrencyName(DictUtils.getDictLabel("currency_code", cjo.getString("Value")));
                    }
                }
                // 汇率
                if(cjo.getString("Name").equals("ExchRate")){
                    tScSettlebill.setExchRate(new BigDecimal(cjo.getString("Value")));
                }
                // 税日期
                if(cjo.getString("Name").equals("TaxDate")){
                    if(!StringUtils.isEmpty(cjo.getString("Value"))){
                        tScSettlebill.setTaxDate(DateUtils.dateTime("yyyyMMdd HH:mm:ss.SSS", cjo.getString("Value")));
                    }
                }
                // 从订单过账
                if(cjo.getString("Name").equals("PostFromCo")){
                    tScSettlebill.setPostFromCo(cjo.getString("Value"));
                    if(StringUtils.isNotEmpty(cjo.getString("Value"))) {
                        tScSettlebill.setPostFromCoName(DictUtils.getDictLabel("post_from_co", cjo.getString("Value")));
                    }
                }
                // 发票备注
                if(cjo.getString("Name").equals("memo")){
                    tScSettlebill.setRemark(cjo.getString("Value"));
                }
            }
            tScSettlebill.setFeeWithoutTax(tScSettlebill.getFee().subtract(tScSettlebill.getTax()));
            tScSettlebill.setPendingFee(tScSettlebill.getFee());
            tScSettlebill.setPendingFeeWithoutTax(tScSettlebill.getFeeWithoutTax());
            // 明细
            List<TScSettlebillEntry> settlebillEntryList = new ArrayList<>();
            for(Object settlebillEntryJo : settlebillEntryJsonArray){
                JSONArray settlebillEntryItemJa = (JSONArray) settlebillEntryJo;
                boolean isSameSettlebill = false;
                // 循环字段
                for(Object oeij : settlebillEntryItemJa){
                    JSONObject cejo = (JSONObject) oeij;
                    // 发票号码
                    if(cejo.getString("Name").equals("InvNum")){
                        // 发票号码一致的明细
                        if(cejo.getString("Value").equals(tScSettlebill.getOrderNo())){
                            isSameSettlebill = true;
                        }
                    }
                }
                if(isSameSettlebill){
                    TScSettlebillEntry tScSettlebillEntry = new TScSettlebillEntry();
                    // 循环字段
                    for(Object oeij : settlebillEntryItemJa){
                        JSONObject cejo = (JSONObject) oeij;
                        // 客户采购单号
                        if(cejo.getString("Name").equals("DerCustPo")){
                            tScSettlebillEntry.setPoNo(cejo.getString("Value"));
                        }
                        // 销售员
                        if(cejo.getString("Name").equals("InvhdrSlsman")){
                            tScSettlebillEntry.setSaleName(cejo.getString("Value"));
                        }
                        // 汇率
                        if(cejo.getString("Name").equals("InvhdrExchRate")){
                            tScSettlebillEntry.setExchRate(new BigDecimal(cejo.getString("Value")));
                        }
                        // 客户订单
                        if(cejo.getString("Name").equals("DerCoNum")){
                            tScSettlebillEntry.setOrderNo(cejo.getString("Value"));
                        }
                        // 客户订单行
                        if(cejo.getString("Name").equals("CoLine")){
                            tScSettlebillEntry.setLineNo(Long.parseLong(cejo.getString("Value")));
                        }
                        // 物料
                        if(cejo.getString("Name").equals("Item")){
                            tScSettlebillEntry.setProductCode(cejo.getString("Value"));
                            tScSettlebillEntry.setSpecificatCode(cejo.getString("Value").replaceAll(" ",""));
                        }
                        // 物料描述
                        if(cejo.getString("Name").equals("Description")){
                            tScSettlebillEntry.setProductName(cejo.getString("Value"));
                        }
                        // 物料描述
                        if(cejo.getString("Name").equals("Spec")){
                            tScSettlebillEntry.setProductName(cejo.getString("Value"));
                        }
                        // 开票数量
                        if(cejo.getString("Name").equals("QtyInvoiced")){
                            tScSettlebillEntry.setQty(new BigDecimal(cejo.getString("Value")));
                        }
                        // 币别
                        if(cejo.getString("Name").equals("CustaddrCurrCode")){
                            tScSettlebillEntry.setCurrencyCode(cejo.getString("Value"));
                            if(StringUtils.isNotEmpty(cejo.getString("Value"))) {
                                tScSettlebillEntry.setCurrencyName(DictUtils.getDictLabel("currency_code", cejo.getString("Value")));
                            }
                        }
                        // 价格
                        if(cejo.getString("Name").equals("Price")){
                            // 不含税需要计算含税金额，反之需要计算不含税金额
                            if(tScSettlebill.getIsTax() == IsTax.NOT_TAX.getCode()){
                                tScSettlebillEntry.setWithoutPrice(new BigDecimal(cejo.getString("Value")));
                            } else{
                                tScSettlebillEntry.setPrice(new BigDecimal(cejo.getString("Value")));
                            }
                        }
                        // 总价格
                        if(cejo.getString("Name").equals("DerExtendedPrice")){
                            // 不含税需要计算含税金额，反之需要计算不含税金额
                            if(tScSettlebill.getIsTax() == IsTax.NOT_TAX.getCode()){
                                tScSettlebillEntry.setWithoutAmount(new BigDecimal(cejo.getString("Value")));
                            } else{
                                tScSettlebillEntry.setAmount(new BigDecimal(cejo.getString("Value")));
                            }
                        }
                        // 单位 UM
                        if(cejo.getString("Name").equals("UM")){
                            tScSettlebillEntry.setUnitCode(cejo.getString("Value"));
                        }
                        // 税码
                        if(cejo.getString("Name").equals("ItmTaxCode1")){
                            if(StringUtils.isNotEmpty(cejo.getString("Value"))){
                                // 查询税率
                                tScSettlebillEntry.setTaxRate(new BigDecimal(DictUtils.getDictValue("tax_rate", cejo.getString("Value"))));
                            }
                        }
                        // 税收编码
                        if(cejo.getString("Name").equals("CommCode")){
                            tScSettlebillEntry.setTaxCategoryCode(cejo.getString("Value"));
                        }
                        // 税收内容
                        if(cejo.getString("Name").equals("CommCodeDescription")){
                            tScSettlebillEntry.setTaxShortName(cejo.getString("Value"));
                        }
                        // 单位描述
                        if(cejo.getString("Name").equals("UMDesc")){
                            tScSettlebillEntry.setUnit(cejo.getString("Value"));
                        }
                    }
                    settlebillEntryList.add(tScSettlebillEntry);
                } else {
                    continue;
                }

            }
            tScSettlebill.setTScSettlebillEntryList(settlebillEntryList);
            settlebillList.add(tScSettlebill);
        }
        return settlebillList;
    }



    public static void main(String[] args) {
        System.out.println(updateSettle("           36","TEST"));
    }
}
